package visual;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.WindowConstants;
import javax.swing.SwingUtilities;

import org.omg.PortableServer._ServantActivatorStub;

import service.network.NetworkFilesystemService;

import materials.matrix.MatrixMaterialInterface;
import materials.network.NetworkInterface;

public class VisualMatrix extends javax.swing.JFrame {

	/**
	* Auto-generated main method to display this JFrame
	*/
	public static void main(String[] args) {
		new VisualMatrix();
	}
	
	
	private NetworkInterface _network;
	
	public VisualMatrix() {
		super();
		initGUI();
		_network = null;
	}
	
	private void initGUI() {
			getContentPane().setLayout(null);
			setSize(400, 300);
			{
				JButton butt  = new JButton("laod");
				butt.setVisible(true);
				butt.setBounds(10, 10, 100, 40);
				butt.addActionListener(new ActionListener() {
					
					@Override
					public void actionPerformed(ActionEvent arg0) {
						loadNetwork();
					}
				});
				getContentPane().add(butt);
			}
			setVisible(true);
	}

	public void loadNetwork(){
		JFileChooser jfc = new JFileChooser();
		jfc.showOpenDialog(this);
		File f = jfc.getSelectedFile();
		NetworkFilesystemService nfss = new NetworkFilesystemService();
		NetworkInterface ni = nfss.loadNetwork(f);
		setNetwork(ni);
		repaintNetData();
	}
	
	public void repaintNetData(){
		x = 10;
		y = 100;
		this.repaint(0, 0, getWidth(), getHeight());
	}
	
	public void updateGUI(NetworkInterface net){
		_network = net;
		repaintNetData();
	}
	
	public void setNetwork(NetworkInterface network){
		_network = network;
	}
	
	int x = 10;
	int y = 100;
	int size = 4;
	
	public void setSize(int i){
		size = i;
	}
	
	public void paint(Graphics g){
		if(_network != null){
			for(int i = 1; i < _network.getLayerNumber(); i++){
				drawMatrix(g,size,x,y,i);
				x += _network.getWeigthMatrix(i).getM()*size +10;
			}
		}
	}
	
	public void drawMatrix(Graphics g,int size,int offsetX, int offsetY, int number){
		MatrixMaterialInterface _data = _network.getWeigthMatrix(number);
		MatrixMaterialInterface factor = _network.getConnectionMatrix(number);
		
		for(int i = 1; i <= _data.getM(); i++){
			for(int j = 1; j <= _data.getN(); j++){
				g.setColor(getColor((_data.getValue(i,j)* factor.getValue(i, j))));
				g.fillRect(offsetX+i*size, offsetY+j*size,size,size);
				g.setColor(Color.white);
			}
			g.setColor(Color.white);
		}
	}
	
	
	private Color getColor(double d){
		if(d < 0.0){
			//return HSV(d);
			return Color.red;
		}else if(d > 0.0){
			//return HSV(d);
			return Color.blue;
		}else if( d == 0.0){
			return Color.green;
		}
		return Color.white;
	}

	private Color HSV(double d) {
		Color c = new Color(Color.HSBtoRGB((float) (1 / (1+Math.pow(Math.E, -(d/2)))), (float)1.0 , (float)1.0));
		return c;
	}
	
	
	

}
